const api = require('../../api/api.js');

Page({
  data: {
    localImgSrc: '',
    region: ['安徽省', '合肥市', '蜀山区']
  },
  onLoad() {
    let that = this;
    wx.getStorage({
      key: 'userId',
      success(e) {
        console.log(e);
        that.setData({
          userId: e.data
        });
      }
    })
  },
  formSubmit(e) {
    let that = this;
    let entName = e.detail.value.name.trim();
    let province = that.data.region[0];
    let city = that.data.region[1];
    let county = that.data.region[2];
    let location = e.detail.value.location.trim();
    let userId = that.data.userId;
    let imgUrl = that.data.localImgSrc;
    if (entName === '' || location === '') {
      wx.showToast({
        title: '请将信息填写完整！',
        icon: 'none'
      })
      return;
    }
    if (imgUrl === '') {
      wx.showToast({
        title: '请选择图片！',
        icon: 'none'
      })
      return;
    }
    wx.showLoading({
      title: '提交中...',
    });
    api.addFile({
      data: {
        userId: userId,
        path: 'enterpriseImage',
        filePath: imgUrl
      },
      success(res) {
        let image = JSON.parse(res.data).fileName;
        api.addEnterprise({
          data: {
            entName,
            province,
            city,
            county,
            location,
            image,
            account: userId
          },
          success(res) {
            if (res.data.flag === true) {
              let pages = getCurrentPages();
              let prePage = pages[pages.length - 2];
              prePage.onLoad();
              that.formitSuccess();
            }
          }
        });
      }
    });
  },
  formitSuccess() {
    wx.hideLoading();
    wx.showToast({
      title: '提交成功！',
    });
    wx.navigateBack({
      delta: '-1'
    });
  },
  pickimg(e) {
    let that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        that.setData({
          localImgSrc: res.tempFilePaths[0]
        });
      }
    })
  },
  delimg() {
    let that = this;
    wx.showModal({
      title: '提示',
      content: '确定取消选中的图片吗？',
      success(e) {
        if (e.confirm) {
          that.setData({
            localImgSrc: ''
          });
        }
      }
    })
  },
  bindRegionChange(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      region: e.detail.value
    })
  }
})